package com.z.utils.weixin.sdk.cp.util;

import com.z.utils.DateUtilsMzywx;
import com.z.utils.IOUtil;
import com.z.utils.weixin.entity.WxCpConfig;
import com.z.utils.weixin.sdk.common.exception.WxErrorException;
import com.z.utils.weixin.sdk.cp.api.IWxCpService;
import com.z.utils.weixin.sdk.cp.bean.WxCpUser;

import java.io.IOException;
import java.util.Date;

public class WxUtil {

	/**
	 * 根据微信回传的code获取企业号信息
	 * @param code
	 * @return
	 * @throws WxErrorException
	 */
	public static WxCpUser getNowWeixinUser(String code, IWxCpService wxCpService) throws WxErrorException {
		WxCpConfig config = WxCpConfigFactory.getWxCpConfig();
		String[] userInfo = wxCpService.oauth2getUserInfo(config, code);
		WxCpUser wxCpUser = wxCpService.userGet(config, userInfo[0]);
		System.out.println("微信认证成功时间:" + DateUtilsMzywx.convertDate2String("yyyy-MM-dd HH:mm:ss", new Date()));
		System.out.println("用户id："+userInfo[0]);
		System.out.println("设备id:"+userInfo[1]);
		return wxCpUser;
	}
	
	/**
	 * 根据微信回传的code获取企业号id和设备id
	 * @param code
	 * @return String数组，第一个为用户id,第二个为设备id。同一微信号同一手机设备号一致，同一手机不同微信号设备号可能会变化
	 * @throws WxErrorException
	 */
	public static String[] getNowWeixinUserInfo(String code, IWxCpService wxCpService) throws WxErrorException {
		String logfileName = "loginLog_" + DateUtilsMzywx.convertDate2String(new Date()) + ".log";
		String timeNow = "[" + DateUtilsMzywx.convertDate2String("HH:mm:ss:SSS", new Date()) + "]";
		WxCpConfig config = WxCpConfigFactory.getWxCpConfig();
		String[] userInfo = null;
		try {
			userInfo = wxCpService.oauth2getUserInfo(config, code);
		} catch (Exception e) {
			try {
				IOUtil.writeFLine(logfileName, "[" + DateUtilsMzywx.convertDate2String("HH:mm:ss:SSS", new Date()) + "]"+timeNow + "获取人员信息失败:" + e.getMessage() + "\r\n");
			} catch (IOException e1) {
			}
			return null;
		}
		try {
			IOUtil.writeFLine(logfileName, "[" + DateUtilsMzywx.convertDate2String("HH:mm:ss:SSS", new Date()) + "]"+timeNow + "用户id："+userInfo[0]+ "\r\n");
			IOUtil.writeFLine(logfileName, "[" + DateUtilsMzywx.convertDate2String("HH:mm:ss:SSS", new Date()) + "]"+timeNow + "设备id:"+userInfo[1] + "\r\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return userInfo;
	}
}
